package com.base.cn.platform.os.controller.manage.main;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.service.course.count.CourseCountService;
import com.base.cn.platform.os.service.exam.count.ExamCountService;
import com.base.cn.platform.os.service.manage.order.count.OrderCountService;
import com.base.cn.platform.os.service.manage.user.count.UserCountService;
import com.base.cn.platform.os.service.manage.work.SysUserWorkBenchService;
import com.base.cn.platform.os.service.manage.work.SysWorkBlockSortService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作台Controller
 *
 * @author s.li
 * @create 2018-04-12 11:39
 */
@Controller
@RequestMapping("/admin/manage/work")
public class UserWorkbenchController extends AdminBaseController {
    @Autowired
    private SysUserWorkBenchService sysUserWorkBenchService;
    @Autowired
    private SysWorkBlockSortService sysWorkBlockSortService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private CourseCountService courseCountService;
    @Autowired
    private ExamCountService examCountService;
    @Autowired
    private OrderCountService orderCountService;

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     * 加载基本数据
     * @return Map<String,Object>
     */
    @RequestMapping("/baseData")
    @ResponseBody
    public Map<String,Object> baseData(){
        Map<String,Object> dataMap = new HashMap<>();
        Map<String,Integer> userCountMap = userCountService.findUserCount();
        dataMap.put("userCountMap",userCountMap);
        Map<String,Integer> courseCountMap = courseCountService.queryCourseCountNum();
        dataMap.put("courseCountMap",courseCountMap);
//        Map<String,Integer> examCountMap = examCountService.queryExamCountNum();
        Map<String,Integer> examCountMap = new HashMap<>();
        dataMap.put("examCountMap",examCountMap);
        Integer orderCount = orderCountService.queryOrderCountNum();
        dataMap.put("orderCount",orderCount);
        Map<String,Object> v96KCountMap = courseCountService.get96KCountData();
        dataMap.put("v96KCountMap",v96KCountMap);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 工作台首页
     * @return
     */
    @RequestMapping("/myWorkbench")
    public String myWorkbench(Model model, HttpServletRequest request){
        JsonObject loginUser = loginUtil.getLoginUser(request);
        Map<String, Object> map = gson.fromJson(loginUser, new TypeToken<Map<String, Object>>() {}.getType());
        model.addAttribute("user", map);
        return resultPage("/manage/main/work/myWorkbench");
    }

    /**
     * 加载工作台数据
     * @param model
     * @param request
     * @return 列表页面
     */
    @RequestMapping("/ajaxQueryWorkbench")
    public String ajaxQueryWorkbench(Model model, HttpServletRequest request){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        List<Map<String,Object>> userWorkBenchList = sysUserWorkBenchService.findUserWordFunctionList(userId);
        if(ObjectUtils.isNotEmpty(userWorkBenchList)){
            //排序
            userWorkBenchList = this.sort(userWorkBenchList,userId);
            model.addAttribute("dataList",userWorkBenchList);
        }
        return resultPage("/manage/main/work/ajaxWorkbench");
    }

    /**
     * 修改工作台权限排序
     * @param request
     * @param paramsList
     * @return
     */
    @RequestMapping("/updateModularSort")
    @ResponseBody
    public Map<String,Object> updateModularSort(HttpServletRequest request,@RequestBody List<Map<String,Object>> paramsList){
        //获取登录用户ID
        BigDecimal useId = loginUtil.getLoginUserId(request);
        return sysWorkBlockSortService.saveSysWorkBlockSort(useId,paramsList);
    }

    /**
     * 排序工作的权限
     * @param paramsList 排序数据内容
     * @return Map<String,Object>
     */
    @RequestMapping("/updateFunctionSort")
    @ResponseBody
    public Map<String,Object> updateFunctionSort(HttpServletRequest request,
                                                 @RequestBody List<Map<String,Object>> paramsList){
        //获取登录用户ID
        BigDecimal useId = loginUtil.getLoginUserId(request);
        return sysUserWorkBenchService.updateWorkFunctionSort(useId,paramsList);
    }

    /**
     * 初始化添加权限页面
     * @param type 类型 provider运营支持，operate内容提供，prepare系统准备
     * @return 列表页面
     */
    @RequestMapping("/initAddNotFunctionList")
    public String initAddNotFunctionList(HttpServletRequest request,
                                         Model model,
                                         @RequestParam("type") String type){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        List<Map<String,Object>> sysFunctionList = sysUserWorkBenchService.queryNotShowFunction(type,userId);
        model.addAttribute("functionList",sysFunctionList);
        return resultPage("/manage/main/work/notAjaxWorkbench");
    }

    /**
     * 添加工作台权限显示
     * @param request HttpServletRequest
     * @param functionIds 显示的权限ID串
     * @param unSelectedIds 不显示的权限ID串
     * @return
     */
    @RequestMapping("/addUserWorkFunction")
    @ResponseBody
    public Map<String,Object> addUserWorkFunction(HttpServletRequest request,
                                                  @RequestParam("functionIds") String functionIds,
                                                  @RequestParam("unSelectedIds") String unSelectedIds){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        return sysUserWorkBenchService.addUserWorkFunction(userId,functionIds,unSelectedIds);
    }
    //==================================

    /***
     * 排序
     * @param userWorkBenchList
     * @return
     */
    private List<Map<String,Object>> sort( List<Map<String,Object>> userWorkBenchList,BigDecimal userId){
        if(ObjectUtils.isNotEmpty(userWorkBenchList)){
            //获取排序数据
            List<Map<String,Object>> sortList = sysWorkBlockSortService.findSysWorkBlockSortByUserId(userId);
            Map<String,Map<String,Object>> sortMaps = new HashMap<>();
            if(ObjectUtils.isNotEmpty(sortList)){
                sortMaps = sortList.stream().collect(Collectors.toMap(e->e.get("blockKey").toString(),e->e));
            }
            //通过工作台类型分组
            Map<Integer,List<Map<String,Object>>> userWorkBenchListMap = userWorkBenchList.stream().collect(Collectors.groupingBy(e->(Integer)((Map<String,Object>)e.get("sysFunction")).get("workType")));
            List<Map<String,Object>> provider = userWorkBenchListMap.get(1);//1运营支持
            List<Map<String,Object>> operate = userWorkBenchListMap.get(2);//2内容提供
            List<Map<String,Object>> prepare = userWorkBenchListMap.get(3);//3系统准备
            //初始化数据集合
            List<Map<String,Object>> dataList = new ArrayList<>(3);
            Map<String,Object> dataMap =new  HashMap<>();
            dataMap.put("list",provider);
            dataMap.put("key","provider");
            Map<String,Object> sortObj = sortMaps.get("provider");
            int sort = 0;
            if(ObjectUtils.isNotEmpty(sortObj)){
                sort = (Integer) sortObj.get("sort");
            }
            dataMap.put("sort",sort);
            dataList.add(dataMap);

            dataMap =new  HashMap<>();
            dataMap.put("list",operate);
            dataMap.put("key","operate");
            sortObj = sortMaps.get("operate");
            if(ObjectUtils.isNotEmpty(sortObj)){
                sort = (Integer) sortObj.get("sort");
            }
            dataMap.put("sort",sort);
            dataList.add(dataMap);

            dataMap =new  HashMap<>();
            dataMap.put("list",prepare);
            dataMap.put("key","prepare");
            sortObj = sortMaps.get("prepare");
            if(ObjectUtils.isNotEmpty(sortObj)){
                sort = (Integer) sortObj.get("sort");
            }
            dataMap.put("sort",sort);
            dataList.add(dataMap);
            //重新排序
            Collections.sort(dataList,(x, y) -> {
                int xSort = (Integer) x.get("sort");
                int ySort = (Integer) y.get("sort");
                if(xSort > ySort){
                    return 1;
                }else if(xSort < ySort){
                    return -1;
                }
                return 0;
            });
            return dataList;
        }
        return null;
    }
}
